﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace XingFuStudio.Pioneer.IO {
    /// <summary>
    /// 自定义类型转换
    /// </summary>
    public static class MyConvert {
        /// <summary>          
        /// 将父类对象转换成子类对象          
        /// </summary>          
        /// <typeparam name="P">父类</typeparam>          
        /// <typeparam name="C">子类</typeparam>          
        /// <param name="parent">父类对象</param>          
        /// <param name="child">子类对象</param>          
        /// <returns>子类对象</returns>          
        public static C ParentToChild<P, C>(P parent, C child)
            where C : P, new() //强制要求C为P子类, 并且允许C使用构造器          
        {
            ////利用反射，重新初始化子类对象              
            //child = (C)Activator.CreateInstance(child.GetType());              
            //初始化子类对象              
            child = new C();

            //  判断子类是否由父类所派生              
            if (child.GetType().BaseType != null && child.GetType().BaseType == parent.GetType()) {
                //获取父类的所有属性                  
                PropertyInfo[] properties = parent.GetType().GetProperties();
                //遍历父类属性                 
                foreach (PropertyInfo property in properties) {
                    //判断是否为可读、可修改的属性                      
                    if (property.CanRead && property.CanWrite) {
                        //赋值子类相应属性值                          
                        property.SetValue(child, property.GetValue(parent, null), null);
                    }
                }
            }
            //返回子类对象              
            return child;
        }
    }
}
